let situation = '';
import env from "../../utils/env";
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    src: '../../image/model.png',
    type: '',
    uPrice: 1,
    photoId: ''
  },
  //岗位
  bindPickerChangeAge: function (e) {
    this.setData({
      job: e.detail.value
    })
  },
  goChat() {
    if (this.data.job != '') {
      wx.navigateTo({
        //目的页面地址
        url: '/pages/interview/index?situation=' + this.data.job,
        success: function (res) {
        }
      })
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '请您选择一个证件类型',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }
  },
  onLoad(options) {
    this.setData({
      src: options.src,
      type: options.type
    })
    this.uploadImage();
  },
  downloadDigitalPhoto() {//下载无水印照片，
    if (!wx.getStorageSync('is_login')) {
      app.login();
    }else if(wx.getStorageSync('is_login')){
      wx.checkSession({
        success: (res) => {
          console.log("session valid");
        },
        fail: (res) => {
          app.login();
          console.log("session invalid");
        },
        complete: (res) => {},
      })
    }
    this.generateOrder1();
  },
  /**生成商户订单 */
  generateOrder1() {
    var third_session = wx.getStorageSync('third_session');
    var Authorization = wx.getStorageSync('access_token');
    var that = this;
    var priceTemp = that.data.uPrice;
    var orderInfo = { "gName": '照片处理服务费', "product": '照片处理服务费', "orderType": '2', "photoId": that.data.photoId, "gPrice": priceTemp, "thirdSession": third_session, "amount": that.data.uPrice }
    console.log(orderInfo);
    console.log(Authorization);

    //统一支付
    wx.request({
      url: env.api_host + '/identify/miniGenerateOrder1',
      method: 'GET',
      header: {
        Authorization: Authorization,
      },
      data: {
        orderInfo: orderInfo,
      },
      success: function (res) {
        var resResult = res.data;
        if (resResult.code == 200) {
          console.log(resResult);
          var payInfo = resResult.data;
          //发起支付
          var param = {
            "timeStamp": payInfo.timeStamp,
            "package": payInfo.package,
            "paySign": payInfo.sign,
            "signType": "RSA",
            "nonceStr": payInfo.nonceStr,
            "priceTemp": priceTemp,
            "prepayId": payInfo.prepayId,
            "appId": payInfo.appId,
            "openId": payInfo.openId
          };
          that.pay(param);
        } else if (resResult.code == 500) {
          wx.showModal({
            title: '温馨提示',
            content: '服务器内部错误，请在【我的】->【联系我们】中反馈',
            complete: (res) => {
              if (res.cancel) {
              }
              if (res.confirm) {
              }
            }
          })
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '服务器没有响应，请在【我的】->【联系我们】中反馈',
            complete: (res) => {
              if (res.cancel) {
              }
              if (res.confirm) {
              }
            }
          })
        }
      },
      complete: function (res) {
        console.log(res);
      }
    })
  },
  /* 支付  */
  pay: function (param) {
    var prepayId = "prepay_id=" + param.prepayId;
    console.log(param);
    console.log(prepayId);
    var _this = this;
    wx.requestPayment({
      openId: param.openId,
      appId: param.prepayId,
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: prepayId,
      signType: "RSA",
      paySign: param.paySign,
      success: function (res) {
        wx.showToast({
          title: '支付成功',
          icon: 'fail',
          duration: 2000
        });
        _this.downloadPhoto(_this.data.photoId);
        wx.navigateTo({
          url: '/pages/order/index',
        })
      },
      fail: function (res) {
        console.log("requestPayment fail");
        wx.showToast({
          title: '支付失败',
          icon: 'fail',
          duration: 2000
        })
      },
      complete: function () {
        console.log("requestPayment complete");
      }
    })
  },
  downloadPhoto(photoId) {
    var _this = this;
    var Authorization = wx.getStorageSync('access_token');
    wx.request({
      url: env.api_host + '/identify/photo/downloadPhoto/' + _this.data.photoId,
      method: 'GET',
      header: {
        Authorization: Authorization,
      },
      success: function (res) {
        if (res.statusCode == 200) {
          var resultData = res.data;
          if (resultData.code == 200) {
            var photoNoWater = resultData.data.cerPhoto;
            _this.savePhoto(photoNoWater);
          }
        }
      },
      fail: function (res) {
        console.log("downloadPhoto fail ");
      },
      complete: function (res) {
        console.log("downloadPhoto complete");

      }
    })
  },
  savePhoto: function (imgSrc) {
    var save = wx.getFileSystemManager();
    var number = Math.random();
    save.writeFile({
      filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.jpg',
      data: imgSrc,
      encoding: 'base64',
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.jpg',
          success: function (res) {
            wx.showToast({
              title: '保存成功',
            })
          },
          fail: function (err) {
            console.log(err);
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail:auth denied") {
              //当初用户拒绝，再次发起授权
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success: () => {
                  wx.openSetting({
                    success(settingdata) {
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击按钮即可保存',
                          showCancel: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败，将无法保存到相册',
                          showCancel: false,
                        })
                      }
                    },
                    fail(failData) {
                      console.log("failData", failData)
                    },
                    complete(finishData) {
                      console.log("finishData", finishData)
                    }
                  })
                }
              })
            }
          },
        })
      }, fail: err => {
        console.log(err)
      }
    })
  },
  goTakePhoto: function () {
    wx.navigateTo({
      //目的页面地址
      url: "/pages/takePhoto/index",
    })
  },
  goAlbum: function () {
    var that = this
    wx.chooseMedia({
      count: 1,
      sizeType:['compressed'],
      mediaType: ['image'],
      sourceType: ['album'],
      maxDuration: 30,
      success(res) {
        wx.showToast({ title: '靓照处理中，请稍后', icon: 'loading', duration: 3000 });
        var fileUrl = res.tempFiles[0].tempFilePath;
        wx.navigateTo({
          //目的页面地址
          url: '/pages/preview/index?src=' + fileUrl + '&type=' + that.data.type,
        })
      }
    })
  },
  uploadImage() {
    const _this = this;
    const thirdSession = wx.getStorageSync('third_session');
    console.log(thirdSession);
    wx.showLoading({
      title: '靓照处理中，请稍后',
      mask: true
    })
    wx.uploadFile({
      url: env.api_host + '/identify/uploadImage',
      filePath: _this.data.src,
      name: 'file',
      formData: {
        type: _this.data.type,
        imgtype: 'store',
        thirdSession: thirdSession
      },
      success(res) {
        var obj = JSON.parse(res.data);
        console.log(obj);
        if (obj.code == 500) {
          wx.showModal({
            title: '温馨提示',
            content: '当前服务器没有响应，请稍后再试',
            showCancel: false,
          })
        } else if (obj.code == -3) {
          wx.showModal({
            title: '温馨提示',
            content: '您提供的照片不满足裁剪要求，请重新上传照片或拍摄',
            showCancel: false,
          })
        } else if (obj.code == -1 || obj.code == -2) {
          wx.showModal({
            title: '温馨提示',
            content: '您提供的照片检测不到符合要求的头像，请重新上传照片或拍摄',
            showCancel: false,
          })
        }
        var base64Image = "data:image/jpeg;base64," + obj.image; // 后台返回的base64数据
        var imgData = base64Image.replace(/[\r\n]/g, '') // 将回车换行换为空字符''
        _this.setData({
          src: imgData,
          photoId: obj.photoId
        })
      },
      fail() {
      },
      complete() {
        //添加wx.hideLoading()一定要添加到complete里
        wx.hideLoading()
      }
    });
  },
  generateOrder: function () {
    wx.navigateTo({
      //目的页面地址
      url: '/pages/orderPreview/index?type=' + this.data.type + "&photoId=" + this.data.photoId,
    })
  },

  /* 支付  */
  pay: function (param) {
    var prepayId = "prepay_id=" + param.prepayId;
    var _this = this;
    wx.requestPayment({
      openId: param.openId,
      appId: param.prepayId,
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: prepayId,
      signType: "RSA",
      paySign: param.paySign,
      success: function (res) {
        wx.showToast({
          title: '支付成功',
          icon: 'fail',
          duration: 2000
        });
        _this.downloadPhoto(_this.data.photoId);
        wx.navigateTo({
          url: '/pages/order/index',
        })
      },
      fail: function (res) {
        console.log("requestPayment fail");
        wx.showToast({
          title: '支付失败',
          icon: 'fail',
          duration: 2000
        })
      },
      complete: function () {
        console.log("requestPayment complete");
      }
    })
  },
  //取消支付
  channelSelect: function () {
    wx.showToast({
      title: "你取消了订单"
    })
    wx.navigateBack({
      delta: 1, // 回退前 delta(默认为1) 页面
      success: function (res) {
        console.log("success");
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function () {
        console.log("fail");
      },
      complete: function () {
        console.log("complete");
      }
    })
  },
})